<template>
  <div class="main-tradebox">
    <div class="top_nav">
          <div class="top_buyorshell flex container">
					<div class="cc_title border-right " @click="navigateTo('/FabiNew/c2cTrade')">
						<p class="font-18 font-bold "><span :class="topBtn==0?'active':''" @click="topmenuTab(0)">购买</span></p>
					</div>
					<span class="splite"></span>
					<div class="cc_title" @click="navigateTo('/FabiNew/C2Cindexsell')">
						<p class="font-18 font-bold"><span :class="topBtn==1?'active':''" >出售</span></p>
					</div>
				</div>
          <!-- 币种列表 -->
          <div class="coin_list container">
            <c2c-aside-comp
                :myData='currencyList'
                @onListClick='onListClick'
              >
            </c2c-aside-comp>
          </div>
    </div>
    <div class="trade-line"></div>
    <!-- 一键买币-->
    <div class="txt_tips">
        <div class="one_btnbuy flex flex-between container" v-if="topBtn==0">
          <div>
            <h3 > <span class="font-20">一键买币</span> <em>小额快速交易，手续费{{coinInfo.rise}}，最小成交量 {{coinInfo.low}}, 单价:{{coinInfo.buy}} CNY</em></h3>
          </div>
          <div class="top_right flex">
            <p>购买数量：</p>
            <el-input placeholder="请输入" v-model="onekeyInput" class="input-with-select" size="small" maxlength="6">
          </el-input>
          <el-button type="warning" size="small" class="m-left-10" @click="oneBuyCoin()" >一键买币</el-button>
          </div>
        </div>
    </div>
    <!-- 自选交易 -->
    <div class="opt_trade "> 
      <div class="container flex-between">
            <div  class="panel-header flex cctie"> 
                <h3 class="font-20 font-bit-bold">{{$t('label450')||'自选交易'}}</h3> 
                <span class="font-12 m-left-15">{{$t('inOrder')}} 更多选择，自由交易</span>
            </div>
            <div class="opt_right">
              <!-- <el-input placeholder="请输入内容" v-model="input3" class="input-with-select" size="small">
                <el-select v-model="select" slot="prepend" placeholder="请选择">
                  <el-option label="100" value="1"></el-option>
                  <el-option label="2000" value="2"></el-option>
                  <el-option label="3000" value="3"></el-option>
                </el-select>
                <el-button slot="append" icon="el-icon-search"></el-button>
              </el-input> -->
            </div>
      </div>
      
    </div>
    <!-- 交易列表 -->
    <div class="cc_toptype">
      <div class="cc_box">
        <!-- 买入、卖出 表格列表 -->
        <!-- 市场挂单 -->
        <div class="panel-container coinmark_list">
          <!-- <div class="break-line"></div> -->
          <!-- <div class="table_list table_fff"> -->
          <div class="table_list container"> 
            <el-table
            :fit='true'
            :max-height='828'
            :data='marketList'
            :header-cell-style="{'background-color':'#ffffff','color':'#787878','font-weight':'bold'}"
          >
            <el-table-column
              width="250"
              :label='$t("ptxt101")'
            >
            <!-- 广告方 -->
              <template slot-scope="scope" class="flex">
              <!-- <span
                v-text="scope.row.type=='0'?$t('buy'):$t('sell')"
                :class="scope.row.type=='0'?'color-danger':'color-success'"
              >
              </span> -->
              <div class="flex flex-v-center username" :data='scope.row.type'>
                <div class="user-list average">
                  <div class="avatar-container middle four">
                    <em class="name">{{scope.row.member.slice(0,1)}}</em><div class="online-icon">
                      <p class="online-status"></p>
                    </div>
                  </div>
                </div>
                <span class="padl15 txt_cg font-bold w110"> {{scope.row.member}}</span>
                <!-- 显示VIP图片 -->
                <img src="../../assets/images/home/v01.png" alt="" srcset="" class="vipimg">
              </div>       
              </template>
            </el-table-column>
            <!-- 数量 -->
            <!-- <el-table-column :label='$t("amount")+"("+coinInfo.coin+")"'> -->
            <el-table-column :label='$t("amount")'>
              <template slot-scope="scope">
                <span :data-id="scope.row.number">{{scope.row.number}} {{scope.row.coin}} </span>
              </template>
            </el-table-column>
            <!-- 价格 单价 -->
            <el-table-column :label='$t("unitPrice")+"(CNY)"'>
              <template slot-scope="scope">
                <!-- {{scope.row.price*1}}  -->
                <span :data-id="scope.row.price" class="t-green">{{scope.row.price}} CNY</span>
              </template>
            </el-table-column>

            <el-table-column
              prop='type'
              label='总额' width="200"
            >
              <template slot-scope="scope">
                <span >{{(scope.row.price*scope.row.number).toFixed(2)}} CNY</span>
              </template>
            </el-table-column>
            <el-table-column
              prop='wdate'
              :label='$t("ptxt102")'  width="160"
            >
              <template slot-scope="scope">
                <span :data-id="scope.row.number">
                  <el-tag type="warning" size="mini" v-if="scope.row.bankcard=='enable'">银行卡</el-tag>
                  <el-tag type="" size="mini" v-if="scope.row.zfb=='enable'">支付宝</el-tag>
                  <el-tag type="success" size="mini" v-if="scope.row.wx=='enable'">微信</el-tag>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              width='130'
              :label='$t("operation")'
            >
              <template slot-scope="scope">
                <el-button type="primary"  size="small" @click="buyCoinBtn(scope.row)">购买 {{scope.row.coin}}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
            <div class="bottom_page" v-if="pageData.page">
              <el-pagination
              background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageData.pagecode"
                :page-sizes="[10, 20,30,40]"
                :page-size="pageData.pagesize"
                layout=" prev, pager, next, total"
                :total="pageData.total">               
              </el-pagination>
            </div>
          </div>
        </div> 
			</div>
    </div>
    <!-- 弹窗 -->
    <!-- 列表买入确认弹窗 -->
    <el-dialog
      title="列表买入提示"
      :visible.sync="buysellProp"
      width="30%"
      center>
      <div class="conmain">
        <div class="flex flex-v-center" >
            <div class="user-list average">
                <div class="avatar-container middle four">
                  <em class="name w40out">{{buyPropData.member||'0'}}</em><div class="online-icon">
                  <p class="online-status"></p>
                </div>
              </div>
            </div>
            <span class="padl15 txt_cg font-bold">{{buyPropData.member}}</span> 
        </div>
        <div class="item_info">
          <div class="flex">
            <p>单价</p><p>{{buyPropData.price}} CNY </p>
          </div>
          <div class="flex">
            <p>订单编号</p><p>{{buyPropData.autoid}} </p>
          </div>
          <!-- <div class="flex">
            <p>交易数量</p><p>{{buyPropData.number}} {{buyPropData.coin}}</p>
          </div> -->
        </div>
      </div>
      <div class="buy_input m-top-10">
        <div class="user_pay m-top-10 prop_payinput">
          <h2>卖方收款方式</h2>
          <div class="flex m-top-10 m-bottom-10 paytypetag">
            <el-tag type="warning" v-if="buyPropData.bankcard=='enable'" >银行卡</el-tag>
            <el-tag type="" v-if="buyPropData.zfb=='enable'" >支付宝</el-tag>
            <el-tag type="success" v-if="buyPropData.wx=='enable'" >微信</el-tag>
          </div>
          <el-form ref="form" :model="sizeForm" label-width="60px" size="mini" :label-position="labelPosition2" class="m-top-15"> 
            <el-form-item label="交易数量">
                <el-input v-model="inputBuyNumber" type="text"></el-input>
            </el-form-item>
            <el-form-item label="交易密码">
                <el-input v-model="inputPaypass" type="password"></el-input>
            </el-form-item>
          </el-form> 
        </div>
      </div>   
      <span slot="footer" class="dialog-footer">
        <el-button @click="buysellProp = false">取 消</el-button>
        <el-button type="primary" @click="buyOrderBtn()">买入</el-button>
      </span>
    </el-dialog>
    
    <!-- 一键买币弹窗 oneBUyProp -->
    <el-dialog
      title="一键买币提示"
      :visible.sync="oneBUyProp"
      width="30%"
      center>
      <div class="conmain">
        <div class="item_info">
          <div class="flex">
            <p>成交单价：</p><p class="font-bold">{{coinInfo.buy*1}} CNY /{{coinInfo.coinid}}</p>
          </div>
          <div class="flex input_boxp">
            <p>成交数量：</p>
            <div class="flex "> <el-input placeholder="请输入" v-model="onekeyInput" class="input-with-select" size="small" maxlength="6"> </el-input>
                <p class="rt_p"> {{coinInfo.coinid}}</p>
            </div>
          </div>
          <div class="flex">
            <p>成交总额：</p><p>{{coinInfo.buy*1*Number(onekeyInput) }} CNY </p>
          </div>
        </div>
        
        <div class="user_pay prop_payinput">
          <el-form ref="form" :model="sizeForm" label-width="100px" size="mini" :label-position="labelPosition" class="m-top-15">
          <el-form-item label="支付方式">
            <div size="medium">
              <el-checkbox border label="银行卡" v-model="checked5" :disabled="payData.khyh=='--'"></el-checkbox>
              <el-checkbox border label="支付宝" v-model="checked6" :disabled="payData.zfbimg=='--'"></el-checkbox>
              <el-checkbox border label="微信" v-model="checked7" :disabled="payData.wximg=='--'"></el-checkbox>
            </div>
          </el-form-item>
          <el-form-item label="交易密码">
              <el-input v-model="inputPaypass" type="password"></el-input>
          </el-form-item>
          </el-form> 
        </div>
      </div>  
      <span slot="footer" class="dialog-footer">
        <el-button @click="oneBUyProp = false">取 消</el-button>
        <el-button type="primary" @click="onebuyFormPost()">下  单</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import TradeConfirm from "@/components/dialogContent/TradeConfirm";
import orderMatch from "@/components/dialogContent/orderMatching";
import orderConfirm from "@/components/dialogContent/OrderConfirm";
import marketOrder from "@/components/dialogContent/MarketOrder";
import orderPaid from "@/components/dialogContent/orderPaid";
import orderDetail from "@/components/dialogContent/orderDetail";
import axios from "axios";
import { checkTradePassword } from "../../service/TradeService.js";
let timer = null;
export default {
  components: {
    TradeConfirm,
    orderMatch,
    orderConfirm,
    marketOrder,
    orderPaid,
    orderDetail
  },
  data() {
    return {
      dialogId: null,
      bindState: null,
      canTrade: false,
      userData: this.userModel,
      operateLable: "卖出",
      operateLabeli18n: "sell",
      coinid: "",
      coinInfo: {

      },
      input3:'',
      myAvailable: 0,
      accountInfo: null,
      buyFormData: {
        price: "",
        number: "",
        total: ""
      },
      imgUrl: "",
      sellFormData: {
        price: "",
        number: "",
        total: ""
      },
      sizeForm: {
          name:'',
          pointid: '',
          coinid: '',
          number: '1',
      },
      confirmData: {},
      //市场挂单弹窗配置
      marketOrderCfg: {
        titlei18nkey: "",
        volumnLabeli18nkey: "",
        title: "市挂单买入",
        volumnLabel: "买入量"
      },
      // 市场挂单
      // marketList: null,
      marketList:[],
      //我发布的订单
      myOrderList: null,
      // 我的c2c交易订单
      myC2COrderList: [],
      // 侧栏列表
      currencyList: [],
      // 订单匹配列表
      orderMatchList: "",
      //订单详情信息
      orderDetail: {},
      //挂单详情
      marketOrderDetail: {},
      // 订单id
      orderId: "",
      //c2c历史订单
      C2CRecord: [],
      //修改申诉状态
			appeal: true,
      coinlist:[],
      onekeyInput:'',
      select: '2',
      buysellProp:false,
      sellCoinBtnProp:false,
      oneBUyProp:false,
      form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
        formLabelWidth: '120px',
        radio2: '3',
        labelPosition:'top',
        labelPosition2:'top',
        allMoney:'',
        buyPropData:{},
        shellPropData:{},
        checked5: null,
        checked6: null,
        checked7: null,
        topBtn:0,
        oneShellProp:false,
        // 卖出
        sellchecked5: null,
        sellchecked6: null,
        sellchecked7: null,
        // type
        bankType:'',
        wxType:'',
        zfbType:'',
        payData:{},
        pageData:{
          // 分页 page 总条数  pagesize每页条数   pagecode页码 type 传 0买入 1 卖出 2 全部
          coin: '',
          type:'sell',
          limit:30,
          pagecode:1,
          page:1,
          total:0,
        },
        inputBuyNumber:'',
        inputPaypass:'',
        shopProp:false,
        shoptrade:{
          selltype:'1',
          price:'',
          number:'',
        },
        userType:'', 
        ruleForm: {
          cny: '',
          autoid: '',
          tradpassword: '',
          number: '',
        },  
        sellCoinBtnPropType:true,
        buyNumber:'',
        total:0,
        proNumber:'',
        
    };
  },
  beforeRouteLeave(to, from, next) {
    if (timer) clearInterval(timer);
    timer = null;
    next();
  },
  watch: {
    shoptrade: {
      handler: function(val, oldVal) {
        console.log("输入的"+val.price,oldVal.price);
        var num= val.price;
        var x = String(num).indexOf('.') + 1; //小数点的位置
        var y = String(num).length - x; //小数的位数
        if(y > 5){
          // this.buyFormData.orderVol=parseFloat(val.orderVol).toFixed(4);
          this.shoptrade.price=this.getPointNum(val.price,2)
          return
        }
      },
      deep: true
    },
    // 买币数量计算
    ruleForm: {
      handler: function(val, oldVal) {
        console.log("输入的"+val.cny,oldVal.cny);
        var Cnynum= val.cny;
        // var x = String(num).indexOf('.') + 1; //小数点的位置
        // var y = String(num).length - x; //小数的位数
        this.ruleForm.number=(Cnynum/this.shellPropData.price).toFixed(8)*1;
        // if(y > 5){
        //   // this.buyFormData.orderVol=parseFloat(val.orderVol).toFixed(4);
        //   return
        // }
        
      },
      deep: true
    },
    'select': function(val,newVal){
      console.log('----val---'+val,newVal);
      if(val==1){
        return  this.rightTxt='CNY'
      }else{
        console.log('val'+321);
        return  this.rightTxt=this.coinInfo.coin;
      }
    },
    '$route.path': function(newVal,oldVal){
       if(newVal === '/FabiNew/C2Cindexsell'){
            console.log('1')
        }else if(newVal === '/FabiNew/c2cTrade'){
            console.log('2')
        }       
    }
  },
  created(){
    if (!this.userData.isLogin) {
        
        return false;
      }else{
        
      }
  },
  mounted() {
    this.fiat_coin().then(res => {
        if (res) {
          this.currencyList = res;
          console.log(this.currencyList);
          
          this.coinInfo = res[0];
          this.coinid=this.coinInfo.coin;
          this.coinInfo.coinid =this.coinInfo.coin;
 
          console.log(this.coinid);
          return Promise.resolve(res[0].coin);
        }
      })
      .then(coin => {
        
        // this.getMyAccount(coin).then(res => {
        //   res && (this.myAvailable = res.usable);
        // });
        return this.fiat_entrust(coin).then(list => {
          this.marketList = list;
        });
      })
      .then(result => {
        if (result) {
          this.Util.sumCalc(result, "price", "number");
          this.marketList = result;
        }
        this.refreshOrder(this.coinInfo.coinid);
      });
  },
  computed: {
    // 购买文字
    buyingLabel() {
      return `${this.$t("buy")}&nbsp;${this.coinInfo.coinid || ""}`;
    },
    // 售卖文字
    sellingLabel() {
      return `${this.$t("sell")}&nbsp;${this.coinInfo.coinid || ""}`;
    },
    // 数量项目
    numberLabel() {
      return `${this.$t("amount")}(${this.coinInfo.coinid || ""})`;
    },
    //金额文字
    amountLabel() {
      return `${this.$t("money")}(CNY)`;
    },
    // 可用
    myAvailableLabel() {
      return `${this.$t("avilable")}&nbsp;${this.myAvailable * 1}&nbsp;${
        this.coinInfo.coinid
      }`;
    },
    //平台指导价
    advisalPrice() {
      return `${this.$t("avisalPrice")}&nbsp;￥${this.coinInfo.cny}`;
    },
    //买入总金额
    buyTotal() {
      return this.buyFormData.price * this.buyFormData.number;
    },
    //卖出总金额
    sellTotal() {
      return this.sellFormData.price * this.sellFormData.number;
    },
    //最少限制
    minNum() {
      return `${this.$t("minNum")} ${this.coinInfo.minnum * 1}`;
    },
    
  },
  methods: {
    getPointNum(num,n){  
        let str = String(num);
        let index = str.indexOf(".");
        let str1 = str.substring(0,index+n+1);
        str1 = Number(str1);
        return str1;
    },
    getuserinfo() {
      this.request(this.api.getuserinfo).then(res => {
        if (res && res.code != "0") {
          this.getDataFaild(res.msg || "获取数据失败");
          return false;
        }
        this.typeinfos = res.data[0];
        // 散户 商户身份
        const c2ctype = res.data[0].isc2csh;
        
        if(c2ctype==0||c2ctype==1){
          this.userType='1';//1 散户  2商户
          localStorage.setItem('usertype', JSON.stringify(c2ctype));
        }else if(c2ctype==2){
          this.userType='2';//1 散户  2商户 
          localStorage.setItem('usertype', JSON.stringify(c2ctype));
        }
      });
    },
    // 列表买入按钮
    buyCoinBtn(rowData){
      if (!this.userData.isLogin) {
        this.errMsg("label120" || "请登录后操作");
        this.navigateTo("/user/login/");
        return false;
      }else{
        // 弹窗
        this.inputBuyNumber='';
        this.inputPaypass='';
        this.buysellProp=true;
        console.log(rowData);
        this.buyPropData=rowData;
      }
    },
    // 列表卖出按钮 弹窗卖出 拆分
    sellCoinBtn(rowData){
      if (!this.userData.isLogin) {
        this.errMsg("label120" || "请登录后操作");
        this.navigateTo("/user/login/");
        return false;
      }else{
        // 弹窗
        this.inputPaypass='';
        this.buysellProp=true;
        console.log(rowData);
        this.shellPropData=rowData;
        this.ruleForm.number=rowData.unfilled;
      }
    },
    // buyOrderBtn 弹窗买入按钮
    buyOrderBtn(){
      if(!this.inputBuyNumber){
        this.errMsg("请填写交易数量");
        return false;
      }
      if(isNaN(this.inputBuyNumber)){
        this.errMsg("请填写正确的交易数量");
        return false;
      }
      if(this.inputPaypass==''){
        this.errMsg("请填写交易密码");
        return false;
      }
      return this.request(this.api.buy_entrust,{autoid:this.buyPropData.autoid,tradpassword:this.inputPaypass,number:this.inputBuyNumber,}).then(res => {
        if (res.code == "0") {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.buysellProp=false;
          return this.fiat_entrust(coinid)
        }else{
          this.errMsg(res.msg);
        }
      });
    },
    topmenuTab(val){
      return
      if(val==0){
        this.topBtn=0;
      }else if(val==1){
        this.topBtn=1;
      }
    },
    //检测交易密码有效性
    checkTradePassword(succCb) {
      if (!this.storage.get("tradePasswordChecked")) {
        this.$prompt(this.$t("label199"), this.$t("label140"), {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /\S/,
          inputType: "password",
          inputErrorMessage: this.$t("label199")
        })
          .then(({ value }) => {
            checkTradePassword(value).then(res => {
              if (res.code != 0) {
                this.storage.set("tradePasswordChecked", false);
                this.errMsg(this.$t("label200"));
              } else {
                this.storage.set("tradePasswordChecked", true);
                succCb && succCb(res);
                this.successMsg(res.msg);
              }
            });
          })
          .catch(() => {});
        return false;
      }
      return true;
    },
    refreshOrder(coin) {
      return
      if (timer) clearInterval(timer);
      timer = setInterval(() => {
        this.fiat_entrust(coin);
        
      }, 60000);
    },
    // 发布订单
    publicOrder(apiKey, param) {
      this.request(apiKey, {
        coin: this.coinInfo.coinid,
        price: param.price || "",
        number: param.number || "",
        showLoading: true
      }).then(res => {
        console.log(`${JSON.stringify(res)}`);
        if (res.code == "0") {
          this.onModelClose();
          this.successMsg(res.msg);
          this.fiat_entrust(this.coinInfo.coinid).then(list => {
            this.marketList = list;
          });
          this.getc2corder();
        } else {
          this.errMsg(res.msg || "操作失败");
        }
      });
      this.fiat_coin()
      .then(res => {
        if (res) {
          this.currencyList = res;
          this.coinInfo = res[0];
          return Promise.resolve(res[0].coinid);
        }
      })
      .then(coin => {
        
        this.getMyAccount(coin).then(res => {
          res && (this.myAvailable = res.usable);
        });
        return this.fiat_entrust(coin).then(list => {
          this.marketList = list;
        });
      })
      .then(result => {
        if (result) {
          this.Util.sumCalc(result, "price", "number");
          this.marketList = result;
        }
        this.refreshOrder(this.coinInfo.coinid);
      });
    },
    //上传凭证
    onChange(e) {
      e.preventDefault();
      let file = e.target.files[0];
      let { name, size, type } = file;
      let formData = new FormData();
      let options = {
        headers: {
          "Content-Type": "MultipartFile/form-data"
        },
        method: "post"
      };
      if (!/\.(jpg|png)$/.test(name)) {
        this.$message.error("图片格式需为jpg或者png");
        return;
      }
      if (size > 4 * Math.pow(1024)) {
        this.$message.error(
          `图片大小不可超过4M,当前图片大小${size / Math.pow(1024, 2)}M`
        );
        return;
      }
      formData.append("imgurl", file);
      options.url = `${this.api.baseURL}/user/img`;
      options.data = formData;
      axios(options).then(res => {
        if (res.data.code == "0") {
          this.successMsg(res.msg || "上传成功");
          this.imgUrl = res.data.data.isFlag;
        }
      });
    },

    //查看凭证
    checkPhoto(photo) {
      if (photo) {
        window.open(photo);
      }
    },
    //{{$t("label212")}}
    cancelRequest(id,value) {
      if (id) {
        this.request(this.api.appeal, {
          id: id,
          info:value
        }).then(res => {
          if (res.data.code == "0") {
            this.successMsg(res.msg || "上传成功");
            this.appeal = false;
          }
        });
      }
    },
    onFileChange(e) {

    },
    // 撤销我的c2c订单
    cancelMyc2cOrder(autoid) {
      if (
        !this.checkTradePassword(() => {
          this.request(this.api.clearc2c, {
            autoid: autoid,
            showLoading: true
          }).then(res => {
            if (res.code == "0") {
              this.successMsg(res.msg || "操作成功");
              this.delItemFromList(autoid, this.myOrderList);
              this.delItemFromList(autoid, this.marketList);
            } else {
              this.errMsg(res.msg || "操作失败");
            }
          });
        })
      ) {
        return false;
      }
      this.request(this.api.clearc2c, {
        autoid: autoid,
        showLoading: true
      }).then(res => {
        if (res.code == "0") {
          this.successMsg(res.msg || "操作成功");
          this.delItemFromList(autoid, this.myOrderList);
          this.delItemFromList(autoid, this.marketList);
        } else {
          this.errMsg(res.msg || "操作失败");
        }
      });
      this.fiat_coin()
      .then(res => {
        if (res) {
          this.currencyList = res;
          this.coinInfo = res[0];
          return Promise.resolve(res[0].coinid);
        }
      })
      .then(coin => {
        
        this.getMyAccount(coin).then(res => {
          res && (this.myAvailable = res.usable);
        });
        return this.fiat_entrust(coin).then(list => {
          this.marketList = list;
        });
      })
      .then(result => {
        if (result) {
          this.Util.sumCalc(result, "price", "number");
          this.marketList = result;
        }
        this.refreshOrder(this.coinInfo.coinid);
      });
    },
    // 删除列表某一项
    delItemFromList(id, listArr) {
      listArr.map((item, index) => {
        console.log(item);
        if (item.autoid == id) {
          listArr.splice(index, 1);
          return listArr;
        }
      });
    },
    // 发布买入
    buyHandle() {
      if (!this.validation()) {
        return;
      }
      if (!isNaN(this.buyTotal) && this.buyTotal > 0) {
        if (
          !this.checkTradePassword(() => {
            this.confirmData = {
              number: this.buyFormData.number,
              price: this.buyFormData.price
            };
            this.dialogId = 0;
          })
        ) {
          return;
        }
        this.confirmData = {
          number: this.buyFormData.number,
          price: this.buyFormData.price
        };
        this.dialogId = 0;
      } else {
        this.errMsg("label121" || "请输入有效价格");
      }
    },
    // 发布卖出
    sellHandle() {
      if (!this.validation()) {
        return;
      }
      if (!isNaN(this.sellTotal) && this.sellTotal > 0) {
        if (
          !this.checkTradePassword(() => {
            this.confirmData = {
              number: this.sellFormData.number,
              price: this.sellFormData.price
            };
            this.dialogId = 1;
          })
        ) {
          return;
        }
        this.confirmData = {
          number: this.sellFormData.number,
          price: this.sellFormData.price
        };
        this.dialogId = 1;
      } else {
        this.errMsg("label121" || "请输入有效价格");
      }
    },
    // 挂单买入/卖出弹窗
    tradeConfirmHandle(rowData) {
      if (!this.userData.isLogin) {
        this.errMsg("label120" || "请登录后操作");
        return false;
      }
      if (!this.checkTradePassword()) {
        return false;
      }
      this.dialogId = 4;
      let type = rowData.type;
      this.marketOrderDetail = {
        ...rowData,
        limitAmount: 0
      };
      this.marketOrderCfg = {
        titlei18nkey: type == 0 ? "sellPendingOrder" : "buyPendingOrder",
        volumnLabeli18nkey: type == 0 ? "sellVol" : "buyVol"
      };
    },
    // 从市场买入/卖出c2c
    tradeFromMarket(type, autoid) {
      if (!this.checkTradePassword()) {
        return false;
      }
      if (!type || !autoid) return false;
      this.request(type == 0 ? this.api.c2cselltrad : this.api.c2cbuytrad, {
        autoid: autoid,
        showLoading: true
      }).then(res => {
        if (res.code == "0") {
          this.onModelClose();
          this.successMsg(res.msg || "操作成功");
          this.fiat_entrust(this.coinInfo.coinid).then(res => {
            this.marketList = res;
          });
          this.getc2corder();
        } else {
          this.errMsg(res.msg || "操作失败");
        }
      });
    },
    // 侧栏点击
    onListClick(data) {
      this.marketList=[];
      this.coinInfo = data;
      console.log(data);
      const coinid =this.coinInfo.coin
      this.coinInfo.coinid=this.coinInfo.coin;
      // this.getc2corder();
      this.fiat_entrust(coinid);
      this.refreshOrder(this.coinInfo.coinid);
      // this.getMyAccount(data.coinid).then(res => {
      //   res && (this.myAvailable = res.usable);
      // });
    },
    // 获取法币交易币种
    fiat_coin() {
      return this.request(this.api.currencylist, {
        showLoading: 0
      }).then(res => {
        console.log(`法币交易币种：${JSON.stringify(res)}`);
        if (res.data && res.data.length > 0) {
          return Promise.resolve(res.data);
        }
      });
    },
    // 获取市场挂单 根据交易币种获取C2C交易市场（分页）
    fiat_entrust(coinid,pageData) {
      return this.request(this.api.getc2cmarketorder, {
        coin:coinid,
        type:this.pageData.type,
        limit:this.pageData.limit,
        page:this.pageData.page,
      }).then(res => {
        // console.log(`市场挂单:${JSON.stringify(res)}`);
        if (res.code == "0") {
          if(res.count==0){
            this.pageData.total=0;
            return
          }
          let list = this.Util.sumCalc(res.data, "price", "number");
          this.marketList=res.data;
          // this.pageData.page=res.data[0].page;
          // this.pageData.pagecode=res.data[0].pagecode;
          this.pageData.total=res.count;
          return Promise.resolve(list);
        } else {
          this.marketList=[];
          return Promise.reject(res);
        }
      });
    },
    //获取资产信息
    getMyAccount(coin) {
      return this.request(this.api.getaccount, {
        search: coin,
        showLoading: true
      }).then(res => {
        console.log(`我的资产：${JSON.stringify(res)}`);
        if (res.code == "0") {
          return Promise.resolve(res.data.list[0]);
        }
      });
    },
    // 操作校验
    validation() {
      if (!this.userData.isLogin) {
        // this.errMsg("label120" || "请登录后操作");
        return false;
      }
      return true;
    },
    //获取的账户状态
    getState() {
      return this.request(this.api.saftyState).then(res => {
        console.log(`账号状态：${JSON.stringify(res)}`);
        if (res && res.code != "0") return this.getDataFaild(res.msg);
        if (res.data && res.data.list) {
          this.bindState = res.data.list[0];
        }
      });
    },
    //确认收付款弹窗
    confirmHandle(rowData) {
      this.dialogId = rowData.type == "0" ? 5 : 6;
      this.orderId = rowData.autoid;
      this.orderDetail = {
        type: rowData.type,
        owner: rowData.type == "0" ? rowData.sellname : rowData.buyname,
        bankCardNo:
          rowData.type == "0" ? rowData.sellbannkcard : rowData.buybannkcard,
        depositBank: rowData.type == "0" ? rowData.sellkhyh : rowData.buykhyh,
        bankBranches: rowData.type == "0" ? rowData.sellkhzh : rowData.buykhzh,
        transferAmount: rowData.zj * 1,
        tel: rowData.tel,
      };
    },
    //查看详情
    confirmDetail(rowData){
      this.dialogId = 6;
      this.orderId = rowData.autoid;
      this.orderDetail = {
        type: rowData.type,
        owner: rowData.type == "0" ? rowData.sellname : rowData.buyname,
        bankCardNo:
          rowData.type == "0" ? rowData.sellbannkcard : rowData.buybannkcard,
        depositBank: rowData.type == "0" ? rowData.sellkhyh : rowData.buykhyh,
        bankBranches: rowData.type == "0" ? rowData.sellkhzh : rowData.buykhzh,
        transferAmount: rowData.zj * 1,
        tel: rowData.tel,
      };
    },
    confirmDetail11(){
      this.dialogId = 7;
    },
    //弹窗关闭
    onModelClose() {
      this.dialogId = null;
    },
    // 处理订单
    dealOrder(type, id) {
      let api = type == "0" ? this.api.setsendok : this.api.setrealyok;
      if (type == 0 && this.imgUrl == "") {
        this.errMsg(this.$t("label198"));
        return false;
      }
      this.request(api, {
        autoid: id,
        photo: this.imgUrl,
        showLoading: true
      }).then(res => {
        if (res.code == "0") {
          this.successMsg(res.msg);
          this.getc2corder();
          this.fiat_entrust(this.coinInfo.coinid).then(list => {
            this.marketList = list;
          });
          
        } else {
          this.errMsg(res.msg);
        }
        this.onModelClose();
      });
    },
    //投诉弹窗
    litter(id) {
      this.$prompt('确定要投诉吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType:"text",
          inputPlaceholder:'问题说明',
          lockScroll:false
        }).then(({ value }) => {
            this.cancelRequest(id,value)
        })
      },
    //一键买入
    oneBuyCoin(){
      if (!this.userData.isLogin) {
        this.errMsg("label120" || "请登录后操作");
        return false;
      }else{
        this.getmypaytype();
      }
      if (isNaN(this.onekeyInput) || !this.onekeyInput) {
        this.errMsg("请输入正确的数量");
        return false;
      }
      this.oneBUyProp=true;
      this.buyNumber=Number(this.onekeyInput);
      this.allMoney=(Number(this.onekeyInput)*Number(this.coinInfo.buy)).toFixed(2);
    },
    // 一键买入 弹窗确定按钮
    onebuyFormPost(){
        this.buyNumber=Number(this.onekeyInput);
        this.allMoney=(Number(this.onekeyInput)*Number(this.coinInfo.buy)).toFixed(2);
      if(this.payData.khyh!="--"){
        this.bankType='enable';
      }else{
        this.bankType='disable';
      }
      if(this.payData.wximg!="--"){
        this.wxType='enable';
        console.log(this.wxType);
      }else{
        this.wxType='disable';
      }
      if(this.payData.zfbimg!="--"){
        this.zfbType='enable';
      }else{
        this.zfbType='disable';
      }
      if(this.zfbType=='disable'&&this.wxType=='disable'&&this.bankType=='disable'){
        this.errMsg("请选择支付或收款方式");
        return false;
      }
      if(this.inputPaypass==''){
        this.errMsg("请填写交易密码");
        return false;
      }
      let promData={
        coin:this.coinInfo.coinid,
        number:this.buyNumber,
        price:this.coinInfo.cny,
        bankcard:this.bankType,
        wx:this.wxType,
        zfb:this.zfbType,
        tradpassword:this.inputPaypass,
        type:'buy',
      }
      return this.sell_entrustPost(promData);
    },
    // 一键买入 数据请求接口
    sell_entrustPost(promData){
      this.request(this.api.add_entrust,promData).then(res => {
            if (res.code == "0") {
              console.log(res); 
              this.$message({message: res.msg,type: 'success'});
              this.oneBUyProp=false;
              this.shopProp=false;
              // 刷新列表
              this.onekeyInput='';
              this.inputPaypass='';
              this.fiat_entrust(this.coinInfo.coinid);
            }else if(res.code==5314){
              this.$message.error(res.msg);//绑定银行卡
              this.navigateTo("/personalCenter/gathering");
            }else if(res.code==5312){
              this.$message.error(res.msg);//绑定身份证
              this.navigateTo("/personalCenter/identify");
            }
            else{
              this.$message.error(res.msg);
            }
      });
    },
    // 一键卖出按钮 011
    oneShellCoin(){
      if (!this.userData.isLogin) {
        this.errMsg("label120" || "请登录后操作");
        return false;
      }else{
        this.getmypaytype();
        this.getuserinfo();
      }
      
      if(this.select==''){
        this.errMsg("请选择买入类型");
        return
      }
      if (isNaN(this.onekeyInput) || !this.onekeyInput) {
        this.errMsg("请输入有效金额或数量");
        return false;
      }
      if(this.sellCoinBtnPropType=false){
        this.oneShellProp=false;
        this.errMsg("请未绑定支付付款方式");
        return
      }else{
        this.oneShellProp=true;
      }
      
        this.buyNumber=Number(this.onekeyInput);
        this.allMoney=(Number(this.onekeyInput)*Number(this.coinInfo.cny)).toFixed(2);
    },
    // 一键卖出弹窗post按钮
    oneShellFormPost(){
      if(this.sellchecked5){
        this.bankType=1;
        console.log(this.bankType);
      }else{
        this.bankType=0;
      }
      if(this.sellchecked6){
        this.wxType=1;
        console.log(this.wxType);
      }else{
        this.wxType=0;
      }
      if(this.sellchecked7){
        this.zfbType=1;
      }else{
        this.zfbType=0;
      }
      if(this.zfbType+this.wxType+this.bankType==0){
        this.errMsg("请选择支付或收款方式");
        return false;
      }
      if(this.inputPaypass==''){
        this.errMsg("请填写交易密码");
        return false;
      }
      let promData={
        coin:this.coinInfo.coinid,
        number:this.buyNumber,
        price:this.coinInfo.cny,
        bankcard:this.bankType,
        wx:this.wxType,
        zfb:this.zfbType,
        tradpassword:this.inputPaypass,
        type:'buy',
      }
      return this.sendsellc2corderPost(promData);
    },
    // 一键卖出函数
    sendsellc2corderPost(promData){
      this.request(this.api.add_entrust,promData).then(res => {
            if (res.code == "0") {
              console.log(res); 
              this.$message({message: res.msg,type: 'success'});
              this.oneShellProp=false;
              this.shopProp=false;
              // 刷新列表
              // this.getc2corder();
              this.fiat_entrust(this.coinInfo.coinid).then(list => {
                this.marketList = list;
              });
            }else if(res.code==5314){
              this.$message.error(res.msg);//绑定银行卡
              this.navigateTo("/personalCenter/gathering");
            }else if(res.code==5312){
              this.$message.error(res.msg);//绑定身份证
              this.navigateTo("/personalCenter/identify");
            }
            else{
              this.$message.error(res.msg);
            }
      });
    },
    // 列表卖出弹窗
    shellOrderBtn(){
      if(this.ruleForm.cny==''||this.ruleForm.number==''){
        this.errMsg("请填写金额及数量");
        return false;
      }
      if(this.ruleForm.cny<this.shellPropData.mincny){
        this.errMsg("购买金额不能小于"+this.shellPropData.mincny);
        return false;
      }
      if(this.inputPaypass==''){
        this.errMsg("请填写交易密码");
        return false;
      }
      return this.request(this.api.sell_entrust,{autoid:this.shellPropData.autoid,tradpassword:this.inputPaypass,number:this.ruleForm.number}).then(res => {
        console.log(`c2c币种${JSON.stringify(res)}`);
        if (res.code == "0") {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.sellCoinBtnProp=false;
          return this.fiat_entrust(coinid)
        }else{
          this.errMsg(res.msg);
          this.sellCoinBtnProp=false;
          return
        }
      });
    },
    // 查询支付方式
    getmypaytype(){
      return this.request(this.api.getmypaytype,).then(res => {
        if (res.code == "0") {
          this.payData=res.data[0];
          if(this.payData.khzh=='--'){
            this.sellchecked5=false;
            this.checked5=false;
            console.log(this.checked5)
          }else if(this.payData.zfbimg=='--'){
            this.sellchecked6=false;
            this.checked6=false;
            console.log(this.checked6)
          }else if(this.payData.wximg!='--'){
            this.sellchecked7=false;
            this.checked7=false;
            console.log(this.checked7)
          }else{
            this.errMsg('请绑定支付收款方式');
            this.sellCoinBtnPropType=false;
            return false
          }
        }else{
          this.errMsg(res.msg);
          return
        }
      });
    },
    //改变时
        // 初始页currentPage、初始每页数据数pagesize和数据data
        handleSizeChange(val) {
            this.pageData.size = val;
            console.log(this.pageData.size)  //每页下拉显示数据
            this.c2corders();
        },    
        //条目改变时
        handleCurrentChange(val) {
          this.pageData.pagecode = val;
          console.log(this.pageData.page)  //点击第几页
          const coinid =this.coinInfo.coin;
          const postDta={
            coin:this.coinInfo.coin,
            type:this.pageData.type,
            limit:30,
            page:this.pageData.page,
          }
          this.fiat_entrust(coinid,postDta) 
        }, 
    // shopC2cProp 商户挂单交易
    shopC2cProp(){
      this.userType=JSON.parse(localStorage.getItem("usertype"));
      if (!this.userData.isLogin) {
        this.errMsg("label120" || "请登录后操作");
        return false;
      }else if(this.userType!=2){
        this.errMsg('您不能进行此项操作');
        return false;
      }else{
        this.getmypaytype();
      }
      this.shopProp=true;
    },
    // 弹窗商户买卖交易
    shopCoinBtn(){
      if(this.sellchecked5){
        this.bankType=1;
        console.log(this.bankType);
      }else{
        this.bankType='disable';
      }
      if(this.sellchecked6){
        this.wxType='enable';
        console.log(this.wxType);
      }else{
        this.wxType='disable';
      }
      if(this.sellchecked7){
        this.zfbType='enable';
      }else{
        this.zfbType='disable';
      }
      if(this.shoptrade.price==''){
        this.errMsg("请填写交易价格");
        return false;
      }
      if(this.shoptrade.number==''){
        this.errMsg("请填写交易数量");
        return false;
      }
      if(this.zfbType+this.wxType+this.bankType==0){
        this.errMsg("请选择支付或收款方式");
        return false;
      }
      if(this.inputPaypass==''){
        this.errMsg("请填写交易密码");
        return false;
      }
      let promData={
        coin:this.coinInfo.coinid,
        number:this.shoptrade.number,
        price:this.shoptrade.price,
        bankcard:this.bankType,
        wx:this.wxType,
        zfb:this.zfbType,
        tradpassword:this.inputPaypass,
        type:this.userType,
      }
      // 单选框切换判断
      if(this.shoptrade.selltype==1){
        // selltype ==1 买入
        console.log(promData.number);
        this.sell_entrustPost(promData);
      }else if(this.shoptrade.selltype==2){
        // selltype ==2 卖币
        console.log(this.shoptrade.number);
        this.sendsellc2corderPost(promData);
      }
    },
    
  }
};
</script>
<style lang="scss" scoped>
.main-tradebox{
  .top_nav{background: #f8fafc;padding: 30px 0 15px 0;}
  .trade-line{height: 8px;background-color: #f2f6fa;}
  .opt_trade{
    margin-top: 24px;
    input{border: 1px solid #bebebe;}
  }
  .cc_toptype{margin-top: 40px;}
  .opt_right{
    .input-with-select{
      .el-input__inner{width:45px;}
    }
  }
}
.main-container {
  min-width: calc(100% - 294px);
  // width: 77%;
  margin: 0 auto;
  .l_title {
    font-size: 20px;
    height: 60px;
    line-height: 60px;
    margin: 20px 0;
    border-radius: 3px;
    padding: 0 30px;
    background: #f1f1f1;
  }
  .l_content {
    border-radius: 3px;
    overflow: hidden;
    padding: 30px;
    background: #f1f1f1;
    line-height: 2;
  }
  .paragraph {
    display: block;
    padding: 30px 0 10px;
    font-size: 14px;
    background: #f1f1f1;
    line-height: 1.5;
  }
}
// 
$border: 1px solid #e5e5e5;
.container {
  min-height: calc(100% - 294px);
  padding: 0px 0;
  width: 77%;
  margin: 0 auto;
  .el-main {
    padding-top: 0;
  }
}
.top_buyorshell{align-items:center;}
.cc_title{
	padding: 0px 15px;cursor: pointer;
  p{
    span{padding: 6px 0;}
    .active{color:black;border-bottom: 2px solid #357ce1;}
  }
	}
.splite {height: 22px;width: 2px;background-color: hsla(0,4%,82%,.5);display: inline-block;margin: 0 20px;}
// 币种列表
.coin_list{
	padding-top: 20px;
	li{
		padding: 0 10px;cursor: pointer;
		p{line-height: 30px;}
		.active{color: #409eff;border-bottom: 2px solid #409eff;}
	}
}
.break-line {
  // @include breakLine;
  border-bottom: 1px solid $bg-darkfoot;
}
span {
  &.color-danger {
    color: $color-danger;
  }
  &.color-success {
    color: $color-success;
  }
}
.upload-file {
  margin-top: 10px;
  input {
    opacity: 0;
    position: absolute;
    z-index: 99;
    height: 100%;
  }
}
.vertical-line {
  height: 360px;
  width: 1px;
  background: $bd-color;
  transform: scaleX(0.5);
  bottom: 0;
}
.photo-preivew {
  margin-top: 20px;
  display: block;
  width: 180px;
  margin-left: 12px;
  img {
    width: 100%;
    max-width:400px;
  }
  &:first-child {
    margin-left: 0;
  }
}
span {
  &.status-0 {
    color: #ccc;
  }
  &.status-1 {
    color: $main-font-color;
  }
  &.status-2 {
    color: $color-success;
  }
  &.status-3 {
    color: $color-danger;
  }
}
$mr: 11px;
.el-container {
  .panel-head {
    margin-bottom: 9px;
    position: relative;
    .thumb-30 {
      margin-right: $mr;
    }
  }
  .market-condition {
    span {
      display: inline-block;
      margin-left: 20px;
    }
    em {
      padding-right: 13px;
    }
  }
  .panel-container {
    .panel-header {
      margin: 10px 0 12px 0;
    }
  }
  .form-wrap {
    width: 48.65%;
    margin-top: 30px;
    .break-line {
      margin-top: 12px;
    }
    .total {
      margin-top: 19px;
    }
    button {
      margin-top: 22px;
    }
    .account {
      margin-top: 14px;
      a {
        color: $color-danger;
      }
    }
    .input-group {
      margin-top: 19px;
      .unit {
        line-height: 40px;
        color: #333;
        padding-right: 6px;
      }
      .el-input {
        margin-top: 10px;
      }
      .hint {
        display: inline-block;
        margin-top: $mr;
      }
    }
  }
}
.hover-em:hover{cursor: pointer}
// 0412代理商
.right_daili{
  span{color: $color-danger;}
}
.marl10{margin-left: 10px;}
.cctie{align-items: flex-end ;}
// copy
.average {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.avatar-container.four {
    background: #b09472;
}
.avatar-container.middle {
    height: 36px;
    width: 36px;
}
.avatar-container {
    height: 32px;
    width: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    position: relative;
}
.avatar-container .name {
    font-size: 14px;
    color: #fff;
    font-style: normal;text-align: center;
}
.avatar-container .online-icon {
    width: 12px;
    height: 12px;
    background: #fff;
    border-radius: 50%;
    position: absolute;
    bottom: 1px;
    left: 22px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.avatar-container .online-icon .online-status {
    width: 6px;
    height: 6px;
    background: #0fd12a;
    border-radius: 50%;
}
.txt_cg{color: #5160a2;}
.w120{width: 120px;}

.with45{width: 45%;}
.form_box{
  .panel-container {
    .panel-header {
      margin: 40px 0 12px 0;
    }
  }
  .form-wrap {
    width: 48.65%;
    margin-top: 30px;
    .break-line {
      margin-top: 12px;
    }
    .total {
      margin-top: 19px;
    }
    button {
      margin-top: 22px;
    }
    .account {
      margin-top: 14px;
      a {
        color: $color-danger;
      }
    }
    .input-group {
      margin-top: 19px;
      .unit {
        line-height: 40px;
        color: #333;
        padding-right: 6px;
      }
      .el-input {
        margin-top: 10px;
      }
      .hint {
        display: inline-block;
        margin-top: $mr;
      }
    }
  }  
}
.coinmark_list{min-height: 60vh}
//背景颜色
.cc-container{min-height: 80vh;}
.el-container {
  border-bottom: 1px solid  #282828;
  border-top:1px solid  #282828;
}  
.color-god{color: #b09472;}
// 弹窗
.item_info{
  margin-top: 10px;
  p{line-height: 30px;font-size: 16px}
  p:nth-child(1){width: 100px;text-align: left;}
}
.w60{width: 60px;text-align: center;}
.user_pay{
  border-top: 1px dashed #bebebe;margin-top: 15px;
  h2{padding: 10px 0;}  
}
.w400{width: 400px;margin-bottom: 20px;}
.w40out{width: 30px;overflow: hidden;}
.paytypetag{
  span{margin-right: 15px;}
}
.bottom_page{margin-top: 15px;}
.vipimg{width: 24px;}
.username .w110{width: 100px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;}



// 1113
.txt_tips{
  padding: 30px 0;background: #f8fafc;
}
.t-green{color: #0da88b;}
.buy_input{
  .form_buy{padding-top: 10px;}
  .fo_input{
    position: relative;
    span{position: absolute;right: 4px;bottom: 0;padding-right: 5px;}
    p{position: absolute;left: 3px;top: 25px;font-size: 12px;color: #f56c6c;}
  }
}
.top_right{
  align-items:center;
  p{width: 150px;}
  button{margin-left: 10px;}
}
.input_boxp{
  padding: 10px 0;
  .rt_p{width:120px;margin-left:15px}
}
</style>